package http

import (
	"bytes"
	"errors"
	"io"
	"net/http"
	"net/url"
	"strconv"
)

// PostRequest - Post请求
func PostRequest(url string, jsonData []byte) ([]byte, error) {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("Failed to post data, status code: " + strconv.Itoa(resp.StatusCode))
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

// GetRequest - Get请求
func GetRequest(reqUrl string, data map[string]string, header map[string]string) ([]byte, error) {
	// 处理请求参数
	params := url.Values{}
	for k, v := range data {
		params.Add(k, v)
	}
	reqUrl = reqUrl + "?" + params.Encode()
	req, err := http.NewRequest("GET", reqUrl, nil)
	if err != nil {
		return nil, err
	}

	for k, v := range header {
		// req.Header.Set("Content-Type", "application/json")
		req.Header.Set(k, v)
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("Failed to get data, status code: " + strconv.Itoa(resp.StatusCode))
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

// PostForm 发送 application/x-www-form-urlencoded 类型的POST请求
func PostForm(url string, data url.Values) ([]byte, error) {
	// 编码表单数据
	formData := data.Encode()

	// 创建请求
	req, err := http.NewRequest("POST", url, bytes.NewBufferString(formData))
	if err != nil {
		return nil, err
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("Failed to get data, status code: " + strconv.Itoa(resp.StatusCode))
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

// PostRequestResponse - Post请求
func PostRequestResponse(url string, jsonData []byte) ([]byte, error) {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("Failed to post data, status code: " + strconv.Itoa(resp.StatusCode))
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}
